#pragma once
#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include"Log.hpp"
#include"InetAddr.hpp"
#include<sys/wait.h>
#include<pthread.h>
#include"ThreadPool.hpp"
#include<functional>

using namespace log_ns;
using namespace std;
const static int gport = 8888;
const static int gsockfd = -1;
const static int gblcklog=8;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERR
};

using task_t = function<void()>;

class TcpServer
{
public:
    TcpServer(uint16_t port = gport):_port(port),_listensockfd(gsockfd),_isrunning(false)
    {
        
    }
    void InitServer()//初始化
    {
         //1.创建套接字
        _listensockfd = socket(AF_INET,SOCK_STREAM,0);//SOCK_STREAM和udp的不一样
        if(_listensockfd<0)
        {
            LOG(FATAL,"socket create failed\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO,"sockfd create success,SOCKFD:%d\n",_listensockfd);//一定是3

        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port=htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        //2.进行绑定
        if(bind(_listensockfd,(struct sockaddr*)&local,sizeof(local))<0)
        {
            LOG(FATAL,"bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO,"bind success\n");
        //3.tcp是面向连接的，所以tcp需要不断地做到获取连接   随时等待新客户到来进行连接
        if(listen(_listensockfd,gblcklog)<0)
        {
            LOG(FATAL,"listen error\n");
            exit(LISTEN_ERR);
        }
        LOG(INFO,"listen success\n");
    }
    class ThreadData
    {
public:
        int _sockfd;
        TcpServer* _self;
        InetAddr _addr;
public:
        ThreadData(int sockfd,TcpServer* self,InetAddr &addr):_sockfd(sockfd),_self(self),_addr(addr)
        {

        }
    };
    void Loop()//启动循环
    {
        _isrunning=true;
        while(_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            //4.获取新连接    _sockfd是获取新连接的一般称为监听套接字，accept的返回值是提供服务的套接字，叫做io套接字
            int sockfd = accept(_listensockfd,(struct sockaddr*)&client,&len);
            if(sockfd<0)
            {
                LOG(WARNING,"accept error\n");
                continue;
            }
            InetAddr addr(client);
            LOG(INFO,"get a new link,client info: %s\n",addr.AddrStr().c_str());

            //单进程版本
            //Service(sockfd,addr);

            //多进程版本
            // pid_t id = fork();
            // if(id==0)
            // {
            //     //子进程,继承了父进程的fd,关闭监听，防止误操作，但继承父进程的连接sockfd
            //     close(_listensockfd);

            //     if(fork() > 0) exit(0);//此时孙子进程变成了孤儿，操作系统会自动吸收

            //     Service(sockfd,addr);
            //     exit(0);
            // }
            // //父进程，关闭文件操作,一直在进行监听,如果不关闭，则会造成文件描述符泄露
            // close(sockfd);
            // int n = waitpid(id, nullptr, 0);
            // if (n > 0)
            // {
            //     LOG(INFO, "wait child success.\n");
            // }

            //多线程版本-----不能关闭fd，因为文件描述表都是共享的
            // pthread_t tid;
            // ThreadData *td = new ThreadData(sockfd, this, addr);
            // pthread_create(&tid,nullptr,Execute,td);//新线程分离

            //线程池版本
            task_t t = bind(&TcpServer::Service,this,sockfd,addr);
            ThreadPool<task_t>::GetInstance()->Equeue(t);
        }
    }
    static void* Execute(void * args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->_self->Service(td->_sockfd,td->_addr);
        delete td;
        return nullptr;
    }

    void Service(int sockfd,InetAddr addr)
    {
        //长服务
        while(true)
        {
            char inbuffer[1024];
            size_t n = read(sockfd,inbuffer,sizeof(inbuffer)-1);//收到消息
            if(n>0)
            {
                inbuffer[n] = 0;
                LOG(INFO, "get message from client %s, message: %s\n", addr.AddrStr().c_str(), inbuffer);

                string echo_string="[server echo]#";
                echo_string+=inbuffer;
                write(sockfd,echo_string.c_str(),echo_string.size());//发送消息
            }
            else if (n == 0)
            {
                LOG(INFO, "client %s quit\n", addr.AddrStr().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error: %s\n", addr.AddrStr().c_str());
                break;
            }
        }
        ::close(sockfd);
    }
    ~TcpServer()
    {

    }
private:
    uint16_t _port;
    int _listensockfd;//获取新连接的
    bool _isrunning;
};